package jp.sourceforge.akjrcp.videotools.dvdtoxvid;


import com.akjava.lib.standards.process.ProcessMonitor;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.ScrolledComposite;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.DirectoryDialog;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.ui.plugin.AbstractUIPlugin;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import jp.sourceforge.akjrcp.akj_betas.Akj_betasPlugin;
import jp.sourceforge.akjrcp.ui.FileOverwriteControler;
import jp.sourceforge.akjrcp.util.PrintStreamProcessPrinter;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class DVDToXvidView extends ViewPart {
	public static Log log=LogFactory.getLog(DVDToXvidView.class);
	
	public static final String ID = DVDToXvidView.class.getName();

	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	DVDTitleSetComposite[] titleSetComposits;

	private Composite composite;

	private DVDData dvdData;

	private ScrolledComposite scroll;

	private Text saveFilePath;
	
	public void createPartControl(Composite parent) {
		//parent.setLayout(new GridLayout(1,false));
		parent.setLayout(new GridLayout());
		Composite actionPanel=new Composite(parent,SWT.NULL);
		actionPanel.setLayout(new RowLayout());
		Button bt=new Button(actionPanel,SWT.NULL);
		ImageDescriptor opendirIcon = AbstractUIPlugin.imageDescriptorFromPlugin(
				Akj_betasPlugin.PLUGIN_ID, "icons/opendir.gif");
	    bt.setImage(opendirIcon.createImage());
	    bt.addSelectionListener(new SelectionListener(){

			public void widgetDefaultSelected(SelectionEvent e) {
				
			}

			public void widgetSelected(SelectionEvent e) {
				openDir();
			}
	    	
	    });
	    
	    
		scroll = new ScrolledComposite(parent,SWT.V_SCROLL|SWT.BORDER);
		GridData gdata=new GridData(GridData.FILL_BOTH);
		gdata.grabExcessVerticalSpace=true;
		//gdata.minimumHeight=200;
		scroll.setLayoutData(gdata);
		
		composite = new Composite(scroll,SWT.NULL);
		//compo.setLayoutData(new GridData(GridData.FILL_BOTH));
		composite.setLayout(new GridLayout(1,false));
		
		dvdData = new DVDData();
		scroll.setContent(composite);
		scroll.setMinSize(SWT.DEFAULT,100);//default
		
		scroll.setExpandHorizontal(true);
		scroll.setExpandVertical(true);
		
		Composite execPanel=new Composite(parent,SWT.NONE);
		execPanel.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		//start button;
		execPanel.setLayout(new GridLayout(3,false));
		Button convertButton=new Button(execPanel,SWT.NULL);
		convertButton.setText("    convert    ");
		convertButton.addSelectionListener(new StartExec());
		
		saveFilePath = new Text(execPanel,SWT.READ_ONLY);
		saveFilePath.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		
		Button saveButton=new Button(execPanel,SWT.NULL);
		saveButton.setText("save");
		saveButton.addSelectionListener(new SaveFile());
		//audio,bitrate
		//file save
		
		//openDir("d:\\video_ts");
		//openDir("e:\\");
	}
	
	public class StartExec implements SelectionListener{

		public void widgetDefaultSelected(SelectionEvent e) {
			
		}

		public void widgetSelected(SelectionEvent e) {
			if(saveFilePath.getText().length()==0){
				return;
			}
			
			if(titleSetComposits==null ||titleSetComposits.length==0){
				return;
			}
			
			DVDTitleSetComposite titleSet=null;
			//get selection title
			for(int i=0;i<titleSetComposits.length;i++){
				if(titleSetComposits[i].getSlected()){
					titleSet=titleSetComposits[i];
					break;
				}
			}
			if(titleSet!=null){
				File files[]=titleSet.getEncodingFile();
				
//				mix start.
				exec(files,new File(saveFilePath.getText()));
			}
			
			
			
			
			
			
		}
		
	}
	
	public String mixCommand(File files[]){
		String ret="";
		for (int i = 0; i < files.length; i++) {
			ret+="\""+files[i].getAbsolutePath()+"\"";
			if(i!=files.length-1){
				ret+="+";
			}
		}
		return ret;
	}
	public void exec(File files[],File export){
		log.info(ArrayUtils.toString(files));
		log.info(export);
		File tmpFile=null;
		try {
			String msCommand="copy /b"+" "+mixCommand(files)+" "+"\""+export+"\"";
			tmpFile=File.createTempFile("tmp", ".bat");
			tmpFile.deleteOnExit();
			FileUtils.writeStringToFile(tmpFile, msCommand);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		String command[]=new String[3];
		command[0]="cmd.exe";
		command[1]="/c";
		command[2]=tmpFile.getAbsolutePath();
		
		
		Runtime r=Runtime.getRuntime();
		try {
			log.info(ArrayUtils.toString(command));
			PrintStreamProcessPrinter s=new PrintStreamProcessPrinter(new PrintWriter(System.out));
			Process process=r.exec(command);
			ProcessMonitor monitor=new ProcessMonitor(process,s);
			monitor.startMonitor();
			try {
				process.waitFor();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	public class SaveFile implements SelectionListener{

		public void widgetDefaultSelected(SelectionEvent e) {
			
		}

		public void widgetSelected(SelectionEvent e) {
			 
			FileDialog dialog=new FileDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),SWT.SAVE);
			dialog.setFilterExtensions(new String[]{"*.avi"});
			dialog.setFilterExtensions(new String[]{"*.vob"});
			String path=dialog.open();
			if(path!=null){
				File f=new File(path);
				if(f.exists()){
					FileOverwriteControler controler=new FileOverwriteControler(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),FileOverwriteControler.MODE_YES_NO_CANCEL);
					boolean r=controler.canOverwrite(f);
					if(r==false){
						return;
					}
				}
				saveFilePath.setText(path);
			}
		}
		
	}
	public void openDir(String path){
		if(path==null){
			return;
		}
		
		Control[] cs=composite.getChildren();
		for (int i = 0; i < cs.length; i++) {
			cs[i].dispose();
		}
		
		//dvdData=new DVDData();
		dvdData.open(new File(path));

		CheckToRadio checkToRadio=new CheckToRadio();
		DVDTitleSet[] titleSets=dvdData.getTitleSets();
		log.info("titleset:"+titleSets.length);
		titleSetComposits=new DVDTitleSetComposite[titleSets.length];
		for(int i=0;i<titleSets.length;i++){
			titleSetComposits[i]=new DVDTitleSetComposite(composite,SWT.NONE,titleSets[i],checkToRadio);
			titleSetComposits[i].setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
		}
		scroll.setMinHeight(140*titleSets.length);
		scroll.pack();
	}
	public void openDir(){
		DirectoryDialog dialog=new DirectoryDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell());
		String path=dialog.open();
		openDir(path);
	}
	public void setFocus() {
		
	}
	
	
	
	
	
		
}